package com.yuda.campsite.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.yuda.campsite.service.ICampsiteConfService;
import com.yuda.campsite.service.PeopleInfoSrevice;
import com.yuda.campsite.service.SendEmaiService;
import com.yuda.campsite.util.SendMailUtil;
import com.yuda.campsite.util.SendNetEaseEmail;
import com.yuda.common.core.constant.HttpStatus;
import com.yuda.common.core.web.domain.AjaxResult;
import com.yuda.common.log.annotation.Log;
import com.yuda.common.log.enums.BusinessType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: xiaohudie
 * @Date: 2021/12/6 14:42
 * @Version: 1.8
 */
@RestController
@RequestMapping("/email")
@Slf4j
public class EmailController {
    @Resource
    private SendMailUtil sendMailUtil;
    @Resource
    private SendNetEaseEmail sendNetEaseEmail;
    @Resource
    private SendEmaiService sendEmaiService;
    @Autowired
    private PeopleInfoSrevice peopleInfoSrevice;
    @Autowired
    private ICampsiteConfService campsiteConfService;


    /**
     * 使用阿里邮箱发送邮件
     */
    @Autowired
    private Client client;


    /**使用阿里邮箱发送邮件*/
    @GetMapping("/sedEmail")
    public AjaxResult sedEmail(String text){
        Map<String,String> map =new HashMap<>();
        map.put("mailAdr","1357494913@qq.com");
        map.put("subject","营地邮箱通知");
        map.put("content",text);
        SendMailUtil.sendMail(map);
        return AjaxResult.success("发送成功");
    }

    @GetMapping("/sendWangYiEmail")
    /**使用网易邮箱发送邮件*/
    public AjaxResult sendWangYiEmail(String to,String text,String title){
        sendNetEaseEmail.sendMail(to, text, title);
         log.info("发送邮件给"+to+"成功");
        return AjaxResult.success("发送邮件成功");
    }


    @GetMapping("/ChaXunIsShengHe")
    public AjaxResult ChaXunIsShengHe(@RequestParam("campsiteId") String  campsiteId){
        String s = peopleInfoSrevice.CampsiteShengHe(campsiteId);
        /**判断是否开启了审核资料，从而返回给前端的列表也不一样*/
        if (s!=null && s.equals("1")){
            List<String> list = new ArrayList<>();
        list.add("进入报名流程");
        list.add("已阅读报名须知");
                list.add("未使用邀请码");
                list.add("已使用邀请码");
                list.add("已填写报名资料");
                list.add("已提交审核材料（未审核）");
                list.add("已提交审核材料（审核通过）");
                list.add("已提交审核材料（审核未通过）");
                list.add("待支付");
                list.add("报名完成");
            return AjaxResult.success("查询列表成功",list);
        }else {
            List<String> list = new ArrayList<>();
            list.add("进入报名流程");
            list.add("已阅读报名须知");
            list.add("未使用邀请码");
            list.add("已使用邀请码");
            list.add("已填写报名资料");
            list.add("待支付");
            list.add("报名完成");
            return AjaxResult.success("查询列表成功", list);
        }

    }


    /**
     * 接受前端 传来的 组合状态
     */
    @Log(title = "发送短信", businessType = BusinessType.OTHER)
    @PostMapping("/sendMessage")
    public AjaxResult sendMessage(@RequestParam("campsiteId") String campsiteId,
                                  @RequestParam("mergeStatus") String mergeStatus,
                                  @RequestParam("subject") String subject,
                                  @RequestParam("text") String text) {
        String[] arr = mergeStatus.split("#");
        int count = 0;
        for (String s : arr) {
            String[] split = s.split(",");
            if (split.length != 3) {return AjaxResult.success("参数不对请传 ，， 样式");}
            AjaxResult ajaxResult = EmailForLd(campsiteId, split[0], split[1], split[2], subject, text);
            if (ajaxResult.get(AjaxResult.CODE_TAG).equals(HttpStatus.SUCCESS)) {
                count++;
            }
        }
        return AjaxResult.success("成功发送短信数量： " + count);
    }

    public AjaxResult EmailForLd(String campsiteId,
                                 String status,
                                 String examineStatus,
                                 String invitationCode,
                                 String subject,
                                 String text) {
        if (status != null && status.equals("-1")) {
            status = null;
        }

        if (examineStatus != null && examineStatus.equals("-1")) {
            examineStatus = null;
        }
        if (invitationCode != null && invitationCode.equals("-1")) {
            invitationCode = null;
        }

        List<String> list = sendEmaiService.ChaXunEmail(campsiteId, status, examineStatus, invitationCode);
        List<String> stringList = sendEmaiService.ChaXunStuEamil(campsiteId, status, examineStatus, invitationCode);
        /**将两个几个进行并集操作*/
        list.addAll(stringList);
        List<String> collect = list.stream().distinct().collect(Collectors.toList());
        if (subject == null) {
            return AjaxResult.error("邮件主题不能为空");
        }
        if (text == null) {
            return AjaxResult.error("邮件内容不能为空");
        }
        for (String s : collect) {
            if (s != null) {
                Map<String, String> map = new HashMap<>();
                map.put("mailAdr", s);
                map.put("subject", subject);
                map.put("content", text);
                SendMailUtil.sendMail(map);
                log.info("已发送的邮箱*************************:" + s);
            }
        }
        return AjaxResult.success("发送成功");
    }

    @Log(title = "发送短信", businessType = BusinessType.OTHER)
    /**前段真实调用的方法*/
    @PostMapping("/SendMessage")
    public AjaxResult SendMessage(@RequestParam("campsiteId") String campsiteId,
                                  @RequestParam("template") String template,
                                  @RequestParam("mergeStatus") String mergeStatus){
        /**将前段传来的参数进行拆分*/
        String[] split = mergeStatus.split("#");
        /**前段需要传模板ID，营地ID，三个参数的组合方式*/
        Integer a =0;
        for (String s : split) {
            String[] split1 = s.split(",");
            AjaxResult ajaxResult = SendMessage2(template, campsiteId, split1[0], split1[1], split1[2]);
            if (ajaxResult.get(AjaxResult.CODE_TAG).equals(HttpStatus.SUCCESS)){
                a++;
            }
        }
        return AjaxResult.success("发送短信成功!");
    }
    /**直接先写发短信的方法*/
    public AjaxResult SendMessage2(String template,
                                  String campsiteId,
                                  String status,
                                  String examineStatus,
                                  String invitationCode){
        if (status != null && status.equals("-1")) {
            status = null;
        }

        if (examineStatus != null && examineStatus.equals("-1")) {
            examineStatus = null;
        }
        if (invitationCode != null && invitationCode.equals("-1")) {
            invitationCode = null;
        }
       /**首先根据前段传过来的营地id,status,examineStatus,invitationCode
        * 来查询具体学生的手机号*/
       /**这是在studentInfo表中的数据*/
        List<String> stringList = sendEmaiService.SelectPhoneStudentInfo(campsiteId, status, examineStatus, invitationCode);
        /**这是在studentAccount表中的数据*/
        List<String> stringList1 = sendEmaiService.SelectPhoneStuAccount(campsiteId, status, examineStatus, invitationCode);
        stringList.addAll(stringList1);
        /**去重并集之后的全部集合*/
        List<String> collect = stringList.stream().distinct().collect(Collectors.toList());
        for (String s : collect) {
            if (s!=null){
                SendSmsRequest sendSmsRequest = new SendSmsRequest();
                sendSmsRequest.setSignName("CAMPCENTER");
                sendSmsRequest.setPhoneNumbers(s);
                sendSmsRequest.setTemplateCode(template);
                JSONObject finalJsonParameters = new JSONObject();
                /**查询该营地名称，这是模板的第一个变量*/
                String s1 = campsiteConfService.SelectYingDiName(campsiteId);
                finalJsonParameters.put("camp_name",s1);
                sendSmsRequest.setTemplateParam(finalJsonParameters.toJSONString());
                try {
                    SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
                    SendSmsResponseBody body = sendSmsResponse.getBody();
                    String message = body.getMessage();
                    String code = body.code;
                    log.info("code为:" +code);
                    log.info("message为:" +message);
                    if(code.equals("OK")) {
                        log.info("已成功发送的手机号码为:***********" + s);
                    }
                    } catch (Exception e) {
                    e.printStackTrace();
                    log.error("发送失败的手机号码：————————————————————————"+s);
                }
            }
        }
        return AjaxResult.success("发送成功",collect.size());
    }
}
